//
//  ZCOutboundCommitViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/4.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCOutboundCommitViewController.h"
#import "UWRQViewController.h"
#import "ZCOutboundPlanModel.h"
#import "ZCPutInStorageTableViewCell.h"
#import "ZCOutboundPlanDetailViewController.h"


static NSString *outboundCellID = @"ZCPutInStorageTableViewCell";

@interface ZCOutboundCommitViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate, uwRQDelegate>
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UITableViewController *tableViewC;
@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UISearchController *searchC;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCOutboundCommitViewController
#pragma mark - 懒加载
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 40)];
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

- (UITableViewController *)tableViewC {
    if (!_tableViewC) {
        _tableViewC = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        _tableViewC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableViewC.tableView.showsVerticalScrollIndicator = NO;
        _tableViewC.tableView.showsHorizontalScrollIndicator = NO;
        _tableViewC.tableView.delegate = self;
        _tableViewC.tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableViewC.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableViewC.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableViewC.tableView.scrollIndicatorInsets = _tableViewC.tableView.contentInset;
            _tableViewC.tableView.estimatedRowHeight = 0;
            _tableViewC.tableView.estimatedSectionFooterHeight = 0;
            _tableViewC.tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableViewC.tableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:outboundCellID];
        
    }
    return _tableViewC;
}

- (UIButton *)scanButton {
    if (!_scanButton) {
        _scanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        [_scanButton setImage:[UIImage imageNamed:@"scanQR"] forState:UIControlStateNormal];
        [_scanButton addTarget:self action:@selector(scanButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scanButton;
}

- (UISearchController *)searchC {
    if (!_searchC) {
        _searchC = [[UISearchController alloc] initWithSearchResultsController:self.tableViewC];
        _searchC.delegate = self;
        _searchC.searchResultsUpdater = self;
        _searchC.searchBar.placeholder = @"请输入订单号/车架号";
        _searchC.searchBar.delegate  = self;
        [_searchC.searchBar addSubview:self.scanButton];
        __weak typeof(self)weakSelf = self;
        [self.scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(weakSelf.searchC.searchBar.mas_centerY);
            make.right.equalTo(weakSelf.searchC.searchBar.mas_right).offset(-15);
        }];
        
    }
    return _searchC;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"出库确认";
    self.definesPresentationContext = YES;
    self.tabBarController.tabBar.hidden = YES;
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    [self.view addSubview:self.searchView];
    [self.searchView addSubview:self.searchC.searchBar];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.listArray removeAllObjects];
    if (self.searchC.searchBar.text.length > 0) {
        [self loadData];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [param setObject:houseId forKey:@"houseId"];
    [param setObject:self.searchC.searchBar.text forKey:@"key"];
    [param setObject:@(1) forKey:@"current"];
    [param setObject:@(10) forKey:@"size"];
    
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:OutboundList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.listArray removeAllObjects];
                for (NSDictionary *dic in responseObject[@"data"]) {
                    ZCOutboundPlanDetailModel *detailModel = [ZCOutboundPlanDetailModel yy_modelWithDictionary:dic];
                    [weakSelf.listArray addObject:detailModel];
                }
                [weakSelf.tableViewC.tableView reloadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 按钮点击
- (void)scanButtonClick:(UIButton *)sender {
    UWRQViewController *uwVC = [[UWRQViewController alloc] init];
    uwVC.delegate = self;
    [self.navigationController pushViewController:uwVC animated:YES];
}

- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - uwRQDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *resArr = [result componentsSeparatedByString:@","];
    NSString *keyId = [resArr firstObject];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [param setObject:houseId forKey:@"houseId"];
    [param setObject:keyId forKey:@"key"];
    [param setObject:@"SCAN" forKey:@"visitType"];
    
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:OutboundDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                if ([responseObject[@"data"] isEqual:[NSNull null]]) {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = @"未查到对应信息";
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }else {
                    [weakSelf.hud hideAnimated:YES];
                    ZCOutboundPlanDetailViewController *detailVC = [[ZCOutboundPlanDetailViewController alloc] init];
                    detailVC.houseId = houseId;
                    detailVC.key = keyId;
                    detailVC.visitType = @"SCAN";
                    detailVC.fromPlan = NO;
                    [weakSelf.navigationController pushViewController:detailVC animated:YES];
                }
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
    
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.tableViewC.view addSubview:self.hud];
    [self loadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.listArray removeAllObjects];
    [self.tableViewC.tableView reloadData];
}

#pragma mark - UISearchControllerDelegate
- (void)willPresentSearchController:(UISearchController *)searchController {
    self.scanButton.hidden = YES;
}

- (void)didDismissSearchController:(UISearchController *)searchController {
    self.scanButton.hidden = NO;
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (searchController.isActive) {
        searchController.searchBar.showsCancelButton = YES;
        UIButton *cancelButton = [searchController.searchBar valueForKey:@"cancelButton"];
        if (cancelButton) {
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
        }
    }
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPutInStorageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:outboundCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.typeTitle = @"发货仓库";
    cell.statusTitle = @"状    态";
    ZCOutboundPlanDetailModel *detailModel = self.listArray[indexPath.row];
    cell.obCommitModel = detailModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(360);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCOutboundPlanDetailViewController *detailVC = [[ZCOutboundPlanDetailViewController alloc] init];
    ZCOutboundPlanDetailModel *detailM = self.listArray[indexPath.row];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    detailVC.houseId = houseId;
    detailVC.key = detailM.Id;
    detailVC.visitType = @"CLICK";
    detailVC.fromPlan = NO;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}


@end
